package com.skcc.cop.mrtaxi.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import android.app.ActivityManager;
import android.app.ActivityManager.RecentTaskInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PermissionInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Vibrator;
import android.provider.Browser;
import android.telephony.TelephonyManager;

public class SystemUtil {

	public static void doVibrat(Context context) {
		Vibrator mVib;
		mVib = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
		mVib.vibrate(500);
	}

	public static String getResStr(Context context, int R_String) {
		Resources res = context.getResources();
		String reStr = res.getString(R_String);
		if (reStr == null) {
			return "";
		}
		return reStr;
	}

	public static String getTelephoneNumber(Context context) {
		TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		// String imsi = mTelephonyMgr.getSubscriberId();
		// String imei = mTelephonyMgr.getDeviceId();
		String phoneNumber = mTelephonyMgr.getLine1Number();
		phoneNumber = phoneNumber.replace("+82", "0");

		return phoneNumber;
		// <uses-permission
		// android:name="android.permission.READ_PHONE_STATE"></uses-permission>
	}

	public static int getAlarmSystem(Context context) {
		AudioManager audioMan = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		return audioMan.getRingerMode();

		// switch (SystemUtil.getAlarmSystem(context)) {
		// case AudioManager.RINGER_MODE_SILENT:
		// AppMan.PRE_MAN.setPrefer(PreferMan.CONF_ALARM, PreferMan.ALARM_NONE);
		// break;
		// case AudioManager.RINGER_MODE_VIBRATE:
		// AppMan.PRE_MAN.setPrefer(PreferMan.CONF_ALARM, PreferMan.ALARM_VIB);
		// break;
		// case AudioManager.RINGER_MODE_NORMAL:
		// AppMan.PRE_MAN.setPrefer(PreferMan.CONF_ALARM, PreferMan.ALARM_BELL);
		// break;
		// }
	}

	// public static void updateGcmRegistration(Context context, String sendId)
	// {
	// Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION);
	// intent.setPackage("com.google.android.gsf");
	// intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
	// PendingIntent.getBroadcast(context, 0, new Intent(), 0));
	// intent.putExtra(GCMConstants.EXTRA_SENDER, sendId);
	// context.startService(intent);
	// }

	public static Intent getFileViewIntent(Context context, File file, String ext) {
		Intent intent = new Intent();
		intent.setAction(android.content.Intent.ACTION_VIEW);
		// ?�일 ?�장??별로 mime type �?��??�?��.
		if (ext.equals("mp3")) {
			intent.setDataAndType(Uri.fromFile(file), "audio/*");
		} else if (ext.equals("mp4")) {
			intent.setDataAndType(Uri.fromFile(file), "vidio/*");
		} else if (ext.equals("jpg") || ext.equals("jpeg") || ext.equals("JPG") || ext.equals("gif")
				|| ext.equals("png") || ext.equals("bmp")) {
			intent.setDataAndType(Uri.fromFile(file), "image/*");
		} else if (ext.equals("txt")) {
			intent.setDataAndType(Uri.fromFile(file), "text/*");
		} else if (ext.equals("doc") || ext.equals("docx")) {
			intent.setDataAndType(Uri.fromFile(file), "application/msword");
		} else if (ext.equals("xls") || ext.equals("xlsx")) {
			intent.setDataAndType(Uri.fromFile(file), "application/vnd.ms-excel");
		} else if (ext.equals("ppt") || ext.equals("pptx")) {
			intent.setDataAndType(Uri.fromFile(file), "application/vnd.ms-powerpoint");
		} else if (ext.equals("pdf")) {
			intent.setDataAndType(Uri.fromFile(file), "application/pdf");
		} else if (ext.equals("hwp")) {
			intent.setDataAndType(Uri.fromFile(file), "application/hwp");
		}

		return intent;

	}

	public static String getStoragePath() {
		String ext = Environment.getExternalStorageState();
		if (ext.equals(Environment.MEDIA_MOUNTED)) {
			return Environment.getExternalStorageDirectory().getAbsolutePath();
		}
		return null;
	}

	public static ArrayList<String> getBrowserHistory(Context context) {
		ArrayList<String> reList = new ArrayList<String>();
		Cursor cursor = Browser.getAllVisitedUrls(context.getContentResolver());
		while (cursor.moveToNext()) {
			String fullUrl = cursor.getString(cursor.getColumnIndex("url"));
			reList.add(getFrontUrl(fullUrl));
		}
		return StringUtil.getSortList(reList);
	}

	private static String getFrontUrl(String fullUrl) {
		String header = "";
		String reStr = "";
		if (fullUrl.substring(0, 7).equals("http://")) {
			header = "http://";
			reStr = fullUrl.replace("http://", "");
		} else if (fullUrl.substring(0, 8).equals("https://")) {
			header = "https://";
			reStr = fullUrl.replace("https://", "");
		}

		int index = reStr.indexOf("/");
		if (index < 0) {
			return header + reStr;
		}
		return header + reStr.substring(0, index);
	}

	public static ArrayList<HashMap<String, String>> getCurrentAppLabel(Context context, int appRecentCount) {
		PackageManager pacMan = (PackageManager) context.getPackageManager();
		ActivityManager actMan = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RecentTaskInfo> infoList = actMan.getRecentTasks(appRecentCount,
				Intent.FLAG_ACTIVITY_NEW_TASK);
		ArrayList<HashMap<String, String>> appList = new ArrayList<HashMap<String, String>>();
		for (int i = 0; i < infoList.size(); i++) {
			String[] appLabel = getAppLabel(pacMan, infoList, i);
			if (appLabel != null) {
				HashMap<String, String> hash = new HashMap<String, String>();
				hash.put("packageName", appLabel[0]);
				hash.put("label", appLabel[1]);
				appList.add(hash);
			}
		}

		return appList;
	}

	public static String getRunningPackageName(Context context) {
		ActivityManager actMan = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		ComponentName localComponentName = ((ActivityManager.RunningTaskInfo) actMan.getRunningTasks(1).get(0)).topActivity;
		return localComponentName.getPackageName();
	}

	private static String[] getAppLabel(PackageManager pacMan, List<ActivityManager.RecentTaskInfo> infoList, int i) {
		ApplicationInfo appInfo = null;
		String[] reStr = new String[2];
		try {
			RecentTaskInfo packInfo = infoList.get(i);
			Intent intent = packInfo.baseIntent;
			reStr[0] = intent.getComponent().getPackageName();
			appInfo = pacMan.getApplicationInfo(reStr[0], 0);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}
		if (appInfo != null) {
			reStr[1] = (String) pacMan.getApplicationLabel(appInfo);
			return reStr;
		}
		return null;
	}

	public static String getAppLabel(Context context, String packageName) {
		PackageManager pacMan = (PackageManager) context.getPackageManager();
		ApplicationInfo appInfo = null;
		try {
			appInfo = pacMan.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}
		if (appInfo != null) {
			return (String) pacMan.getApplicationLabel(appInfo);
		}
		return null;
	}

	public static boolean isPackageExist(Context context, String packageName) {
		PackageManager pacMan = (PackageManager) context.getPackageManager();
		ApplicationInfo appInfo;
		try {
			appInfo = pacMan.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
		} catch (NameNotFoundException e) {
			// e.printStackTrace();
			return false;
		}
		if (appInfo != null && !appInfo.packageName.equals("")) {
			return true;
		}
		return false;
	}

	public static String getPackageInstallDate(Context context, String packageName) {
		PackageManager packMan = (PackageManager) context.getPackageManager();
		ApplicationInfo appInfo = null;
		try {
			appInfo = packMan.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
		} catch (NameNotFoundException e) {
			// e.printStackTrace();
			return "";
		}

		String appFile = appInfo.sourceDir;
		long installed = new File(appFile).lastModified(); // Epoch Time
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
		String dateString = formatter.format(new Date(installed));

		if (dateString == null) {
			dateString = "";
		}
		return dateString;
	}

	public static String getPackageInstallMemory(Context context, String packageName) {
		PackageManager packMan = (PackageManager) context.getPackageManager();
		ApplicationInfo appInfo = null;
		try {
			appInfo = packMan.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
		} catch (NameNotFoundException e) {
			// e.printStackTrace();
			return "";
		}

		String reStr = "";
		try {
			String appFile = appInfo.sourceDir;
			long installed = new File(appFile).length();
			installed = installed + new File(appInfo.dataDir).length();
			double nCalcVal = Math.round(((double) installed / 1000000.0) * Math.pow(10, 1)) / Math.pow(10, 1);
			reStr = nCalcVal + "M";
		} catch (Exception e) {
			return "";
		}

		return reStr;
	}

	public static Drawable getPackageIcon(Context context, String packageName) {
		PackageManager packMan = (PackageManager) context.getPackageManager();
		try {
			return packMan.getApplicationIcon(packageName);
		} catch (NameNotFoundException e) {
			// e.printStackTrace();
			return null;
		}
	}

	public static String[] getPermissionInfo(Context context, String permName) {
		PackageManager packMan = (PackageManager) context.getPackageManager();
		PermissionInfo permissionInfo;
		String[] reStr = { "", "" };
		try {
			permissionInfo = packMan.getPermissionInfo(permName, PackageManager.GET_META_DATA);
			reStr[0] = (String) permissionInfo.loadLabel(packMan);
			reStr[1] = (String) permissionInfo.loadDescription(packMan);
		} catch (NameNotFoundException e) {
			// e.printStackTrace();
			reStr = null;
		}
		return reStr;
	}

	public static boolean isGooglePlaySource(Context context) {
		PackageManager packMan = (PackageManager) context.getPackageManager();
		String packageName = getPackageName(context);
		String unknown = null;
		try {
			unknown = packMan.getInstallerPackageName(packageName);
		} catch (Exception e) {
			unknown = null;
			return false;
		}
		if (unknown == null) {
			return false;
		}
		return true;
	}

	public static String getPackageName(Context context) {
		return context.getPackageName();
	}

	public static boolean isServiceAlive(Context context, String packageAndClassName) {
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> info = am.getRunningServices(200);

		for (Iterator iterator = info.iterator(); iterator.hasNext();) {
			RunningServiceInfo runningTaskInfo = (RunningServiceInfo) iterator.next();
			if (runningTaskInfo.service.getClassName().contains(packageAndClassName)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @param context
	 * @param packageName
	 *            com.mcu.lib
	 * @param className
	 *            .asset.ClassName
	 * @return
	 */
	public static boolean isServiceAlive(Context context, String packageName, String className) {
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> info = am.getRunningServices(200);

		for (Iterator iterator = info.iterator(); iterator.hasNext();) {
			RunningServiceInfo runningTaskInfo = (RunningServiceInfo) iterator.next();
			if (runningTaskInfo.process.equals(packageName)
					&& runningTaskInfo.service.getClassName().equals(packageName + className)) {
				return true;
			}
		}
		return false;
	}

	public static boolean isServiceRunning(Context context, String packageName) {
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> info = am.getRunningServices(200);

		for (Iterator iterator = info.iterator(); iterator.hasNext();) {
			RunningServiceInfo runningTaskInfo = (RunningServiceInfo) iterator.next();
			if (runningTaskInfo.service.getPackageName().equals(packageName)) {
				return true;
			}
		}
		return false;
	}

	public static boolean isProcessRunning(Context context, String packageName) {
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> info = am.getRunningAppProcesses();

		for (Iterator iterator = info.iterator(); iterator.hasNext();) {
			RunningAppProcessInfo runningTaskInfo = (RunningAppProcessInfo) iterator.next();
			if (runningTaskInfo.processName.equals(packageName)) {
				return true;
			}
		}
		return false;
	}

	public static String getLocaleInfo(Context context) {
		Locale systemLocale = context.getResources().getConfiguration().locale;
		String strDisplayCountry = systemLocale.getDisplayCountry();
		String strCountry = systemLocale.getCountry();
		String strLanguage = systemLocale.getLanguage();
		return strLanguage;
	}
}
